package com.meida.module.bus.provider.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.util.TypeUtils;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.meida.common.mybatis.base.service.impl.BaseServiceImpl;
import com.meida.common.mybatis.entity.EntityMap;
import com.meida.common.mybatis.model.ResultBody;
import com.meida.common.mybatis.query.CriteriaQuery;
import com.meida.common.mybatis.query.CriteriaSave;
import com.meida.common.mybatis.query.CriteriaUpdate;
import com.meida.common.security.OpenHelper;
import com.meida.common.utils.DateUtils;
import com.meida.common.utils.FlymeUtils;
import com.meida.module.admin.client.entity.BaseUser;
import com.meida.module.admin.provider.service.BaseUserService;
import com.meida.module.bus.client.entity.*;
import com.meida.module.bus.provider.api.service.SyncOAService;
import com.meida.module.bus.provider.api.service.SyncSrmService;
import com.meida.module.bus.provider.api.util.ApiConstants;
import com.meida.module.bus.provider.api.util.PmsApiUtil;
import com.meida.module.bus.provider.api.util.PmsOaUtil;
import com.meida.module.bus.provider.mapper.BusMaterialMapper;
import com.meida.module.bus.provider.mapper.BusMaterialPlan200Mapper;
import com.meida.module.bus.provider.service.*;
import com.meida.module.bus.provider.utils.CommonUtil;
import com.meida.module.bus.provider.utils.LevelNoUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 200材料计划表接口实现类
 *
 * @author flyme
 * @date 2020-10-22
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class BusMaterialPlan200ServiceImpl extends BaseServiceImpl<BusMaterialPlan200Mapper, BusMaterialPlan200> implements BusMaterialPlan200Service {

    @Autowired
    private SyncSrmService syncSrmService;
    @Autowired
    private BusPurchaseDetailsService busPurchaseDetailsService;
    @Autowired
    private BusPurchaseService busPurchaseService;
    @Autowired
    private BusMaterialSrmService busMaterialSrmService;
    @Autowired
    private BusVersionService busVersionService;
    @Autowired
    private BusMaterialService busMaterialService;
    @Resource
    private BusMaterialMapper busMaterialMapper;
    @Autowired
    private BusMaterialPlan200Service busMaterialPlan200Service;
    @Autowired
    private BusProjectService busProjectService;
    @Autowired
    private PmsOaUtil pmaOaUtil;
    @Autowired
    private BaseUserService baseUserService;

    @Autowired
    LevelNoUtil levelNoUtil;
    @Autowired
    private BusMajorService busMajorService;

    @Autowired
    private SyncOAService syncOAService;

    @Autowired
    CommonUtil commonUtil;
    @Autowired
    private PmsApiUtil pmsApiUtil;

    @Override
    public ResultBody beforeAdd(CriteriaSave cs, BusMaterialPlan200 bmp, EntityMap extra) {
        BusProject project= busProjectService.getById(bmp.getProjectId());
        if (FlymeUtils.isEmpty(project)) {
            return ResultBody.failed("项目信息不存在");
        }
        Integer state = project.getState();
        if (state == 1) {
            return ResultBody.failed("项目已锁定");
        }
        return ResultBody.ok();
    }


    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)
    public ResultBody beforePageList(CriteriaQuery<BusMaterialPlan200> cq, BusMaterialPlan200 bmp, EntityMap requestMap) {
        if (FlymeUtils.isNotEmpty(requestMap.get("type")) && requestMap.get("type").equals("1")) {
            cq.addSelect("bmep.materialPlanId,bmep.parentId,bmep.materialId,bmep.projectId,bmep.versionId,bmep.brandName,bmep.packageNo," +
                "bmep.packageName,bmep.majorCode,bmep.subjectName,bmep.materialWbsCode,bmep.materialCode,bmep.materialDesc, bmep.levelNo,bmep.contractDesc,bmep.materialArea,bmep.materialUse," +
                "bmep.materiaSpecs,bmep.technicalData,bmep.materialName,bmep.costQuantity100,bmep.costQuantity200,bmep.measurementUnit,bmep.loss,bmep.majorName,bmep.caseType,bmep.receivedDate,bmep.purchaseCount,bmep.vendorName,bmep.planPurchaseCount," +
                "bmep.endPurchaseCount,bmep.ztPurchaseCount,bmep.dhPurchaseCount,bmep.orderflg,bmep.status,bmep.applayStatus,bmep.planType,bmep.instructNumber,bmep.vendorId," +
                " material.conversionUnit,material.mainPrice,material.mainAmount," +
                " material.contractSyntheticalPrice3,material.unitBillQuantity100,material.convertBillQuantity100," +
                " material.unitBillQuantity200,material.convertBillQuantity200,material.convertPurchaseCount");
            cq.addSelect("concat(version.bigVersion,'.',version.smallVerion) as 'ver',project.projectName,projectCode,user.userName,project.updateTime as versionTime,project.projectId as projectIds ,version.versionId as versionIds");
            cq.isNull("bmep.parentId");
            cq.notLike("bmep.materialCode", ApiConstants.MATERIALCODE_MASTER_MARK);
            if(FlymeUtils.isNotEmpty(requestMap.get("applyStatus"))&&FlymeUtils.isNotEmpty(requestMap.get("purseApplayStatus"))){
                cq.eq("bmep.purseApplayStatus", requestMap.get("purseApplayStatus"));
                cq.eq("bmep.applayStatus", requestMap.get("applyStatus"));
            }
        }else{
            cq.addSelect("bmep.materialPlanId,bmep.parentId,bmep.materialId,bmep.projectId,bmep.versionId,bmep.brandName,bmep.packageNo," +
                "bmep.packageName,bmep.majorCode,bmep.subjectName,bmep.materialWbsCode,bmep.materialCode,bmep.materialDesc, bmep.levelNo,bmep.contractDesc,bmep.materialArea,bmep.materialUse," +
                "bmep.materiaSpecs,bmep.technicalData,bmep.materialName,bmep.costQuantity100,bmep.costQuantity200,bmep.measurementUnit,bmep.loss,bmep.majorName,bmep.planPurchaseCount," +
                "bmep.endPurchaseCount,bmep.ztPurchaseCount,bmep.dhPurchaseCount,bmep.purchaseCount,bmep.receivedDate,bmep.orderflg,bmep.status,bmep.applayStatus,bmep.planType,bmep.instructNumber,bmep.vendorId,bmep.vendorName,bmep.caseType," +
                "material.conversionUnit,material.mainPrice,material.mainAmount," +
                "material.contractSyntheticalPrice3,material.unitBillQuantity100,material.convertBillQuantity100," +
                "material.unitBillQuantity200,material.convertBillQuantity200,material.convertPurchaseCount");
            cq.addSelect("concat(version.bigVersion,'.',version.smallVerion) as 'ver',project.projectName,projectCode,user.userName,project.updateTime as versionTime,project.projectId as projectIds ,version.versionId as versionIds");

        }
        cq.createJoin(BusProject.class).setMainField("projectId").setJoinField("projectId");
        cq.createJoin(BusVersion.class).setMainAlias("project").setMainField("versionId").setJoinField("versionId");
        cq.createJoin(BusMaterial.class).setMainField("materialId").setJoinField("materialId");
        cq.createJoin(BaseUser.class).setMainAlias("version").setJoinField("userId").setJoinField("userId");
        if (FlymeUtils.isNotEmpty(requestMap.get("projectId"))) {
            cq.eq("bmep.projectId", requestMap.get("projectId"));
        } else {
            cq.groupBy("project.versionId");
        }
        Long userId = OpenHelper.getUserId();
        List<String> userMajorList = busMajorService.getUserMajors(userId);
        if (userMajorList.size() > 0) {
            if (!userMajorList.contains("P99")) {
                cq.in("bmep.majorCode", userMajorList);
            }
        }
        cq.like("project.projectName", requestMap.get("projectName"));
        cq.like("project.projectCode", requestMap.get("projectCode"));
        cq.eq("bmep.projectId", requestMap.get("projectId"));
        cq.like("bmep.packageNo", requestMap.get("packageNo"));
        cq.like("bmep.packageName", requestMap.get("packageName"));
        cq.like("bmep.majorName", requestMap.get("majorName"));
        cq.like("bmep.majorCode", requestMap.get("majorCode"));
        cq.like("bmep.packageName", requestMap.get("packageName"));
        cq.like("bmep.packageNo", requestMap.get("packageNo"));
        cq.like("bmep.materialWbsCode", requestMap.get("materialWbsCode"));
        cq.like("bmep.materialCode", requestMap.get("materialCode"));
        cq.like("bmep.materialName", requestMap.get("materialName"));
        cq.like("bmep.levelNo", requestMap.get("levelNo"));
        cq.like("bmep.subjectName", requestMap.get("subjectName"));
        cq.like("bmep.materialArea", requestMap.get("materialArea"));
        cq.like("bmep.materialUse", requestMap.get("materialUse"));
        cq.eq("bmep.materialId", requestMap.get("materialId"));
        if(FlymeUtils.isNotEmpty(requestMap.get("versionId"))){
            cq.eq("bmep.versionId",requestMap.get("versionId"));
        }
        if(FlymeUtils.isNotEmpty(requestMap.get("planType"))){
//            //修正变更
//            if(requestMap.get("planType").equals("1")){
//                cq.isNull("bmep.instructNumber");
//                cq.isNotNull("bmep.parentId");
//            }
//            //追加变更
//            if(requestMap.get("planType").equals("2")){
//                cq.isNotNull("bmep.instructNumber");
//                cq.isNotNull("bmep.parentId");
//            }
            cq.eq("bmep.planType",requestMap.get("planType"));
        }
        if(FlymeUtils.isNotEmpty(requestMap.get("versionStatus"))){
            cq.eq("bmep.versionStatus",requestMap.get("versionStatus"));
        }
        if(FlymeUtils.isNotEmpty(requestMap.get("applayStatus"))){
            cq.eq("bmep.applayStatus",requestMap.get("applayStatus"));
        }
        cq.orderByDesc("bmep.updateTime");
        cq.orderByAsc("bmep.levelNo");
        return ResultBody.ok();
    }

    @Override
    public ResultBody updateMaterial(Long projectId, Long versionId, BusPurchase purchase) throws Exception {
        BusProject project= busProjectService.getById(projectId);
        if (FlymeUtils.isEmpty(project)) {
            return ResultBody.failed("项目信息不存在");
        }
        Integer state = project.getState();
        if (state == 1) {
            return ResultBody.failed("项目已锁定");
        }
        if (FlymeUtils.isNotEmpty(purchase.getDetails())) {
            List<BusPurchaseDetails> bLis = new ArrayList<>();
            List<BusMaterialPlan200> pnlist = new ArrayList<>();
            for (BusPurchaseDetails se : purchase.getDetails()) {
                BusMaterialPlan200 plan100 = getById(se.getMaterialId());
                if (FlymeUtils.isNotEmpty(plan100)) {
                    if (FlymeUtils.isNotEmpty(se.getPurchaseNum())) {
                        if (se.getPurchaseNum().compareTo(plan100.getEndPurchaseCount()) > 0) {
                            return ResultBody.failed("本次采购量不能大于剩余采购量");
                        }
                        plan100.setPurchaseCount(se.getPurchaseNum());//本次采购量
                        plan100.setZtPurchaseCount(plan100.getZtPurchaseCount().add(se.getPurchaseNum()));//在途数量=本次采购量+原材料明细在途数量
                        plan100.setEndPurchaseCount(plan100.getEndPurchaseCount().subtract(se.getPurchaseNum()));//剩余采购计划量
                    } else {
                        return ResultBody.failed("采购量不为空");
                    }
                    if (FlymeUtils.isNotEmpty(se.getReceivedDate())) {
                        String date = se.getReceivedDate().substring(0, 10);
                        plan100.setReceivedDate(DateUtils.formatDate(date));
                        se.setReceivedDate(DateUtils.formatDate(date));
                    } else {
                        return ResultBody.failed("计划到货时间不能为空");
                    }
                    plan100.setDhPurchaseCount(BigDecimal.ZERO);
                    plan100.setApplayStatus(0);
                    plan100.setOrderflg("0");//订单下达
                    if (FlymeUtils.isNotEmpty(se.getVendorName())) {
                        plan100.setVendorName(se.getVendorName());
                    }
                    if (FlymeUtils.isNotEmpty(se.getDocumentType())) {
                        plan100.setCaseType(se.getDocumentType());
                    }
                    pnlist.add(plan100);
                    // 在途数量
                    se.setOnLineNum(se.getPurchaseNum());
                    // 到货数量
                    se.setReceiveNum(BigDecimal.ZERO);
                }
            }
            if (FlymeUtils.isNotEmpty(pnlist)) {
                boolean cd = saveOrUpdateBatch(pnlist);
            }
            BaseUser baseUser = baseUserService.getUserById(OpenHelper.getUserId());
            boolean a = busPurchaseDetailsService.saveBatch(purchase.getDetails());
            boolean b = busPurchaseService.save(purchase);
            Map applyMap=new HashMap();
            applyMap.put("plan200detail",pnlist);
            applyMap.put("purchase",purchase);
            applyMap.put("purchaseDetail",purchase.getDetails());
            updatepurseApplayStatus(projectId,pnlist);//更新状态为审核中
            int status= syncOAService.approval(applyMap, "/approvl/purseDetail200", OpenHelper.getUserName(), ApiConstants.ENGINEER_APPROVAL_WZ_REQ ,projectId.toString());
            if(status==1){
                ResultBody.ok("材料审批发送成功，等待审批");
            }
        }

        return ResultBody.ok();
    }
    @Override
    public Boolean updatepurseApplayStatus(Long projectId, List<BusMaterialPlan200> plan200s) {
        if(FlymeUtils.isNotEmpty(plan200s)) {
            for (BusMaterialPlan200 se : plan200s) {
                se.setPurseApplayStatus(1);
                se.setApplayStatus(1);
            }
        }
        return saveOrUpdateBatch(plan200s);
    }


    @Override
    public Boolean goApplyStatus(Long projectId, Integer applayStatus) {
        CriteriaUpdate<BusMaterialPlan200> cu = new CriteriaUpdate<>();
        cu.eq("projectId", projectId);
        cu.eq("applayStatus", "1");//审核中的状态
        cu.eq("versionStatus", 0);
        cu.set("applayStatus", applayStatus);
        cu.set("versionStatus", 1);
        return update(cu);
    }

    @Override
    public ResultBody mergeplan200(Map map) {
        Long projectId = FlymeUtils.getLong(map.get("projectId"));
        BusProject project= busProjectService.getById(projectId);
        if (FlymeUtils.isEmpty(project)) {
            return ResultBody.failed("项目信息不存在");
        }
        Integer state = project.getState();
        if (state == 1) {
            return ResultBody.failed("项目已锁定");
        }
        String userName = OpenHelper.getUserName();
        Integer type = TypeUtils.castToInt(map.get("dataType"));
        pmsApiUtil.setPlanPackageDataToReqMap(map, projectId, null, null, type, type == 1 ? ApiConstants.ENGINEER_APPROVAL_WZ_200_UPD : ApiConstants.ENGINEER_APPROVAL_WZ_200_ADD);
        int approvalResult = 0;
        if (type == 1) {
            approvalResult = syncOAService.approval(map, "/approvl/bmep200UpdateDetail", userName, ApiConstants.ENGINEER_APPROVAL_WZ_200_UPD, projectId.toString());
        }
        if (type == 2) {
            approvalResult = syncOAService.approval(map, "/approvl/bmep200AddDetail", userName, ApiConstants.ENGINEER_APPROVAL_WZ_200_ADD, projectId.toString());
        }
        if (ApiConstants.APPROVAL_SUCCESS == approvalResult) {
            updateApplayStatus(projectId, type,ApiConstants.WZ_APPLYSTATUS_AUDIT_ING);
            return ResultBody.ok("OA审批提交成功");
        } else {
            updateApplayStatus(projectId, type, ApiConstants.WZ_APPLYSTATUS_AUDIT_WAIT);
            return ResultBody.failed("OA审批提交失败");
        }

    }
    @Override
    public Boolean updateApplayStatus(Long projectId, Integer planType, Integer applayStatus) {
        List<String> majorCodes=busMajorService.getUserMajors(OpenHelper.getUserId());
        CriteriaUpdate<BusMaterialPlan200> cu = new CriteriaUpdate<>();
        cu.eq("projectId", projectId);
        cu.eq("planType", planType);
        cu.eq("versionStatus", 0);
        //提交之前的数据都叫待审核，只需要修改这部分的数据
        cu.eq("applayStatus", ApiConstants.WZ_APPLYSTATUS_AUDIT_WAIT);
        if (majorCodes.size() > 0) {
            if (!majorCodes.contains("P99")) {
                cu.in("majorCode",majorCodes);
            }
        }
        cu.set("applayStatus", applayStatus);
        return update(cu);
    }

    @Override
    public ResultBody goPurseSuccess(Integer checkState, Long projectId, List<BusMaterialPlan200> plan200List, BusPurchase purchase, String userNm) {
        if (checkState == ApiConstants.APPROVAL_REJECT) {//审核驳回
            //释放本彩采购量到计划采购量中
            for (BusMaterialPlan200 plan200 :plan200List){
                plan200.setEndPurchaseCount(plan200.getPurchaseCount().add(plan200.getEndPurchaseCount()));
                plan200.setZtPurchaseCount(plan200.getZtPurchaseCount().subtract(plan200.getPurchaseCount()));
                plan200.setPurseApplayStatus(1);
                plan200.setApplayStatus(ApiConstants.WZ_APPLYSTATUS_AUDIT_NOPASS);
            }
            saveOrUpdateBatch(plan200List);
        }
        //审批通过

        if (checkState == ApiConstants.APPROVAL_SUCCESS) {
            try {
                //审核通过发起srm
                //释放本彩采购量到计划采购量中
                for (BusMaterialPlan200 plan200 :plan200List){
                    plan200.setPurseApplayStatus(1);
                    plan200.setApplayStatus(ApiConstants.WZ_APPLYSTATUS_AUDIT_PASS);
                }
                saveOrUpdateBatch(plan200List);
                int orderRequest = syncSrmService.materialRequest(purchase, userNm);
                if (orderRequest == 0) {
                    return ResultBody.ok("材料申请成功", purchase);
                } else {
                    return ResultBody.ok("材料申请失败");
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return ResultBody.ok();
    }

    @Override
    public ResultBody gomergeplan200(Integer checkState,Long projectId) {
      // goApplyStatus(projectId,2);
        //审核通过
        if (checkState == ApiConstants.APPROVAL_SUCCESS) {
            Boolean b = pmaOaUtil.updateMaterialBase(projectId, ApiConstants.VER_200, ApiConstants.INT_ZERO);
            if (b) {
                //将审核通过的新增的数据，属于父节点的，版本改为正式版本
                CriteriaUpdate<BusMaterialPlan200> cu = new CriteriaUpdate<BusMaterialPlan200>();
                cu.eq("projectId", projectId);
                cu.eq("applayStatus", ApiConstants.WZ_APPLYSTATUS_AUDIT_PASS);
                cu.eq("versionStatus", 0);
                cu.eq("parentId", 0);
                cu.set("versionStatus", ApiConstants.INT_ONE);
                cu.set("parentId", null);
                update(cu);
                return ResultBody.ok("合并子节点成功");
            }
        }
        return ResultBody.failed("合并子节点失败");
    }
    @Override
    public List<EntityMap> initPurchseDataplans(Map map) {
        List<Long> materialPlanIds = new ArrayList<>();
//        if(FlymeUtils.isNotEmpty(map.get("materialPlanIds"))){
//            String [] ids=map.get("materialPlanIds").toString().split(",");
//            for(String planid200:ids){
//                materialPlanIds.add(Long.parseLong(planid200));
//            }
//        }
        CriteriaQuery<BusMaterialPlan200> cq = new CriteriaQuery(BusMaterialPlan200.class);
        cq.addSelect(BusMaterialPlan200.class, "materialPlanId", "materialId", "parentId", "projectId", "versionId", "brandName", "packageNo",
            "packageName", "majorCode", "subjectName", "materialWbsCode", "materialCode", "materialDesc", "vendorName", "caseType",
            " levelNo", "contractDesc", "materialArea", "materialUse", "materiaSpecs", "technicalData", "materialName", "costQuantity100", "costQuantity200", "measurementUnit", "loss",
            " majorName", "planPurchaseCount", "endPurchaseCount", "ztPurchaseCount", "dhPurchaseCount", "purchaseCount", "receivedDate", "orderflg", "status", "applayStatus", "planType");
        cq.addSelect(BusProject.class, "projectCode", "projectName");
        cq.addSelect(BusMaterial.class, "conversionUnit", "mainPrice", "mainAmount",
            "contractSyntheticalPrice3", "unitBillQuantity100", "convertBillQuantity100",
            "unitBillQuantity200", "convertBillQuantity200");
//        cq.addSelect("supplier.supplierName as vendorId, dictdata.dicDataTitle as  caseType");
        cq.createJoin(BusProject.class).setMainField("projectId").setJoinField("projectId");
        cq.createJoin(BusMaterial.class).setMainField("materialId").setJoinField("materialId");
//        cq.createJoin(BusSupplier.class).setMainField("vendorId").setJoinField("supplierId");
//        cq.createJoin(SysDictData.class).setMainField("caseType").setJoinField("dicDataValue");
        cq.like("bmep.packageNo", map.get("packageNo"));
        cq.like("bmep.packageName", map.get("packageName"));
        cq.like("bmep.majorName", map.get("majorName"));
        cq.like("bmep.majorCode", map.get("majorCode"));
        cq.like("bmep.packageName", map.get("packageName"));
        cq.like("bmep.packageNo", map.get("packageNo"));
        cq.like("bmep.materialWbsCode", map.get("materialWbsCode"));

        cq.like("bmep.materialName", map.get("materialName"));
        cq.like("bmep.levelNo", map.get("levelNo"));
        cq.like("bmep.subjectName", map.get("subjectName"));
        cq.like("bmep.materialArea", map.get("materialArea"));
        cq.like("bmep.materialUse", map.get("materialUse"));
        Long userId = OpenHelper.getUserId();
        List<String> userMajorList = busMajorService.getUserMajors(userId);
        if (userMajorList.size() > 0) {
            if (!userMajorList.contains("P99")) {
                cq.in("bmep.majorCode", userMajorList);
            }
        }
        cq.eq("bmep.projectId", map.get("projectId"));
        cq.isNull("bmep.parentId");
        cq.notLike("bmep.materialCode", ApiConstants.MATERIALCODE_MASTER_MARK);
//        cq.orderByDesc("bmep.updateTime");
        cq.orderByAsc("bmep.levelNo");
        return selectEntityMap(cq);
    }

    @Override
    public ResultBody copyAndUpdateplan(Map map) {
        String copyDataStr = (String) map.get("copyDataStr");
        Long projectId = TypeUtils.castToLong(map.get("projectId"));
        BusProject project = busProjectService.getById(projectId);
        if (FlymeUtils.isEmpty(project)) {
            return ResultBody.failed("项目信息不存在");
        }
        Integer state = project.getState();
        if (state == 1) {
            return ResultBody.failed("项目已锁定");
        }
        Integer type = TypeUtils.castToInt(map.get("type"));
        BusVersion latestVersion = busVersionService.getLatestVersion(projectId, 1);
        if (FlymeUtils.isEmpty(latestVersion)) {
            return ResultBody.failed("无版本信息");
        }
        BusVersion newBusVersion = new BusVersion();
        BeanUtils.copyProperties(latestVersion, newBusVersion);
        String smallVerion = newBusVersion.getSmallVerion();
        Integer small = TypeUtils.castToInt(smallVerion) + 1;
        if (small < 10) {
            smallVerion = "0" + small;
        } else {
            smallVerion = TypeUtils.castToString(small);
        }
        newBusVersion.setSmallVerion(smallVerion);
        Long versionId = IdWorker.getId();
        newBusVersion.setUserId(OpenHelper.getUserId());
        newBusVersion.setVersionId(versionId);
        newBusVersion.setCreateTime(DateUtils.getNowDateTime());
        newBusVersion.setState(0);
        newBusVersion.setVersionType(1);
        busVersionService.saveOrUpdate(newBusVersion);
        project.setVersionId(versionId);
        project.setUserId(OpenHelper.getUserId());
        busProjectService.saveOrUpdate(project);
        List<BusMaterialPlan200> busMaterialPlan200List = JSON.parseArray(copyDataStr, BusMaterialPlan200.class);
        List<BusMaterial> bBusMaterialList = new ArrayList<>();
        for (BusMaterialPlan200 busMaterialPlan200 : busMaterialPlan200List) {
            BusMaterial busMaterial = busMaterialService.getById(busMaterialPlan200.getMaterialId());
            BusMaterial newl = new BusMaterial();
            BeanUtils.copyProperties(busMaterial, newl);
            Long materialId = IdWorker.getId();
            newl.setMaterialId(materialId);
            newl.setParentId(busMaterialPlan200.getMaterialId());
            newl.setProjectId(projectId);
            busMaterialPlan200.setCostQuantity200(busMaterialPlan200.getCostQuantity200());
            busMaterialPlan200.setPlanPurchaseCount(busMaterialPlan200.getCostQuantity200().multiply(busMaterialPlan200.getLoss()));
//            busMaterialPlan200.setDisplayplanPurchaseCount(busMaterialPlan200.getCostdisplayQuantity200().multiply(busMaterialPlan200.getLoss()));
            busMaterialPlan200.setEndPurchaseCount(busMaterialPlan200.getCostQuantity200().multiply(busMaterialPlan200.getLoss()));
            busMaterialPlan200.setZtPurchaseCount(BigDecimal.ZERO);
            busMaterialPlan200.setDhPurchaseCount(BigDecimal.ZERO);
            busMaterialPlan200.setPurchaseCount(BigDecimal.ZERO);
            busMaterialPlan200.setOrderflg("0");
//            newl.setMainPrice(busMaterial.getMainPrice());
//            newl.setMainPrice1(busMaterial.getMainPrice2());
//            newl.setMainPrice2(busMaterial.getMainPrice3());
//            newl.setMainPrice3(busMaterial.getMainPrice3());
//            newl.setInstallPrice(busMaterial.getInstallPrice());
//            newl.setInstallPrice1(busMaterial.getInstallPrice1());
//            newl.setInstallPrice2(busMaterial.getInstallPrice2());
//            newl.setInstallPrice3(busMaterial.getInstallPrice3());
//            newl.setMainAmount(busMaterial.getMainPrice().multiply(busMaterialPlan200.getCostQuantity100().add(busMaterial.getMainPrice().multiply(busMaterialPlan200.getCostQuantity200()))));//成本主材费
//            newl.setMainAmount1(busMaterial.getMainPrice1().multiply(busMaterialPlan200.getCostQuantity100().add(busMaterial.getMainPrice1().multiply(busMaterialPlan200.getCostQuantity200()))));
//            newl.setMainAmount2(busMaterial.getMainPrice2().multiply(busMaterialPlan200.getCostQuantity100().add(busMaterial.getMainPrice2().multiply(busMaterialPlan200.getCostQuantity200()))));
//            newl.setMainAmount3(busMaterial.getMainPrice3().multiply(busMaterialPlan200.getCostQuantity100().add(busMaterial.getMainPrice3().multiply(busMaterialPlan200.getCostQuantity200()))));
//            newl.setInstallAmount(busMaterial.getInstallPrice().multiply(busMaterialPlan200.getCostQuantity100().add(busMaterial.getInstallPrice().multiply(busMaterialPlan200.getCostQuantity200()))));//成本安装费
//            newl.setInstallAmount1(busMaterial.getInstallPrice1().multiply(busMaterialPlan200.getCostQuantity100().add(busMaterial.getInstallPrice1().multiply(busMaterialPlan200.getCostQuantity200()))));
//            newl.setInstallAmount2(busMaterial.getInstallPrice2().multiply(busMaterialPlan200.getCostQuantity100().add(busMaterial.getInstallPrice2().multiply(busMaterialPlan200.getCostQuantity200()))));
//            newl.setInstallAmount3(busMaterial.getInstallPrice3().multiply(busMaterialPlan200.getCostQuantity100().add(busMaterial.getInstallPrice3().multiply(busMaterialPlan200.getCostQuantity200()))));
//            newl.setSyntheticalPrice1(busMaterial.getSyntheticalPrice1());//有合同综合价
//            newl.setSyntheticalPrice2(busMaterial.getSyntheticalPrice2());//拟合同综合价
//            newl.setSyntheticalPrice3(busMaterial.getSyntheticalPrice3());//合同综合价
//            newl.setSyntheticalPrice(busMaterial.getSyntheticalPrice());//预算成本综合价
//            newl.setMainsumPrice1(busMaterial.getMainsumPrice1());
//            newl.setMainsumPrice2(busMaterial.getMainsumPrice2());
//            newl.setMainsumPrice3(busMaterial.getMainsumPrice3());
//            newl.setInstallsumPrice1(busMaterial.getInstallsumPrice1());
//            newl.setInstallsumPrice2(busMaterial.getInstallsumPrice2());
//            newl.setInstallsumPrice3(busMaterial.getInstallsumPrice3());
//            newl.setContractsumSyntheticalPrice1(
//                busMaterial.getMainsumPrice1().multiply(busMaterialPlan200.getCostQuantity100()
//                    .add(busMaterial.getMainsumPrice1().multiply(busMaterialPlan200.getCostQuantity200())))
//                    .add( busMaterial.getInstallsumPrice1().multiply(busMaterialPlan200.getCostQuantity100()
//                        .add(busMaterial.getInstallsumPrice1().multiply(busMaterialPlan200.getCostQuantity200())))));
//            newl.setContractsumSyntheticalPrice2(
//                busMaterial.getMainsumPrice2().multiply(busMaterialPlan200.getCostQuantity100()
//                    .add(busMaterial.getMainsumPrice2().multiply(busMaterialPlan200.getCostQuantity200())))
//                    .add( busMaterial.getInstallsumPrice2().multiply(busMaterialPlan200.getCostQuantity100()
//                        .add(busMaterial.getInstallsumPrice2().multiply(busMaterialPlan200.getCostQuantity200()))))
//            );
//            newl.setContractsumSyntheticalPrice3(
//                busMaterial.getMainsumPrice3().multiply(busMaterialPlan200.getCostQuantity100()
//                    .add(busMaterial.getMainsumPrice3().multiply(busMaterialPlan200.getCostQuantity200())))
//                    .add( busMaterial.getInstallsumPrice3().multiply(busMaterialPlan200.getCostQuantity100()
//                        .add(busMaterial.getInstallsumPrice3().multiply(busMaterialPlan200.getCostQuantity200()))))
//            );

            bBusMaterialList.add(newl);
            //修正版本信息
            busMaterialPlan200.setMaterialId(materialId);

            busMaterialPlan200.setVersionId(versionId);
            busMaterialPlan200.setCreateTime(DateUtils.getNowDateTime());
            busMaterialPlan200.setUpdateTime(null);
            if (FlymeUtils.isNotEmpty(busMaterialPlan200.getParentId())) {
                busMaterialPlan200.setParentId(busMaterialPlan200.getParentId());
            } else {
                busMaterialPlan200.setParentId(busMaterialPlan200.getMaterialPlanId());
            }
            //添加操作类型
            if(FlymeUtils.isNotEmpty(map.get("planType"))){
                busMaterialPlan200.setPlanType(Integer.parseInt(map.get("planType").toString()));
            }
            Long parentId1 = busMaterialPlan200.getParentId();
            String packageNo = busMaterialPlan200.getPackageNo();
            String redisKey = "plan200_" + parentId1;
            String levelNo = levelNoUtil.getLevelNo(redisKey, packageNo, busMaterialPlan200.getLevelNo());
            busMaterialPlan200.setLevelNo(levelNo);
            busMaterialPlan200.setMaterialPlanId(IdWorker.getId());
            busMaterialPlan200.setVersionStatus(0);
            busMaterialPlan200.setApplayStatus(ApiConstants.WZ_APPLYSTATUS_AUDIT_WAIT);//待审核状态
        }
        if (busMaterialPlan200List.size() > 0) {
            saveBatch(busMaterialPlan200List);
            busMaterialService.saveBatch(bBusMaterialList);
        }
        return ResultBody.ok();
    }

    @Override
    public ResultBody import200PurseDetail(MultipartFile file, Map params) {
        try {
            ImportParams importParams = new ImportParams();
            importParams.setTitleRows(1);
            List<BusMaterialPlan200> busMaterialPlan200List = new ArrayList<>();
            List<Map<Object, Object>> ExcelList = ExcelImportUtil.importExcel(file.getInputStream(), Map.class, importParams);
            int i = 1;
            for (Map<Object, Object> objectObjectMap : ExcelList) {
                if(!objectObjectMap.get("计量单位").equals(objectObjectMap.get("物料单位"))) {
                    return ResultBody.failed("存在计量单位与物料单位不一致的材料申请");
                }
                EntityMap entityMap = new EntityMap();
                objectObjectMap.forEach((k, v) -> {
                    if (v == null || v.equals("null")) {
                        v = "";
                        objectObjectMap.put(k, v);
                    }
                });
                Long materialplan200Id = TypeUtils.castToLong(objectObjectMap.get("编号"));
                BusMaterialPlan200 plan200 = getById(materialplan200Id);
                BusProject project= busProjectService.getById(plan200.getProjectId());
                if (FlymeUtils.isEmpty(project)) {
                    return ResultBody.failed("项目信息不存在");
                }
                Integer state = project.getState();
                if (state == 1) {
                    return ResultBody.failed("项目已锁定");
                }
                String isUpdate = String.valueOf(objectObjectMap.get("是否修改"));
                if (isUpdate.equals("否")) {
                    continue;
                }
                BigDecimal purchaseCount = TypeUtils.castToBigDecimal(objectObjectMap.get("本次采购量"));
                String receivedDate = TypeUtils.castToString(objectObjectMap.get("计划到货时间"));
                String caseType = TypeUtils.castToString(objectObjectMap.get("单据类型"));
                String vendorName = TypeUtils.castToString(objectObjectMap.get("班组"));
                if (FlymeUtils.isEmpty(purchaseCount)) {
                    return ResultBody.failed("请核对第" + i + "行本次采购量为空");
                }
                if (FlymeUtils.isEmpty(receivedDate)) {
                    return ResultBody.failed("请核对第" + i + "行计划到货时间为空");
                }
                plan200.setVendorName(vendorName);
                plan200.setPurchaseCount(purchaseCount);
                plan200.setCaseType(caseType);
                plan200.setReceivedDate(DateUtils.formatDate(receivedDate));
                busMaterialPlan200List.add(plan200);
                i++;
            }
            if(busMaterialPlan200List.size()>0){
                String key = String.valueOf(IdWorker.getId());
                redisUtils.setList(key, busMaterialPlan200List, 3600);
                return ResultBody.ok(key);
            }else{
                return ResultBody.failed("当前excel没有要处理的数据");
            }
        } catch (Exception e) {
            return ResultBody.failed("导入失败");
        }
    }

    @Override
    public List<EntityMap> initDataplans(Map map) {
        CriteriaQuery<BusMaterialPlan200> cq = new CriteriaQuery(BusMaterialPlan200.class);
        cq.addSelect(BusMaterialPlan200.class, "*");
        cq.addSelect(BusProject.class, "projectCode", "projectName");
        cq.addSelect(BusMaterial.class, "conversionUnit,mainPrice,mainAmount," +
            "contractSyntheticalPrice3,unitBillQuantity100,convertBillQuantity100," +
            "unitBillQuantity200,convertBillQuantity200");
        cq.like("project.projectCode", map.get("projectCode"));
        cq.like("project.projectName", map.get("projectName"));
        cq.like("bmep.majorName", map.get("majorName"));
        cq.like("bmep.majorCode", map.get("majorCode"));
        cq.like("bmep.packageName", map.get("packageName"));
        cq.like("bmep.packageNo", map.get("packageNo"));
        cq.like("bmep.materialWbsCode", map.get("materialWbsCode"));
        cq.like("bmep.materialName", map.get("materialName"));
        cq.like("bmep.levelNo", map.get("levelNo"));
        cq.like("bmep.subjectName", map.get("subjectName"));
        cq.like("bmep.materialArea", map.get("materialArea"));
        Long userId = OpenHelper.getUserId();
        List<String> userMajorList = busMajorService.getUserMajors(userId);
        if (userMajorList.size() > 0) {
            if (!userMajorList.contains("P99")) {
                cq.in("bmep.majorCode", userMajorList);
            }
        }
        cq.ge("bmep.status", "2");
        cq.eq("project.projectId", map.get("projectId"));
        cq.eq("bmep.versionId", map.get("versionId"));
//        cq.orderByAsc("bmep.createTime");
        cq.orderByAsc("bmep.levelNo");
        cq.createJoin(BusProject.class).setMainField("projectId").setJoinField("projectId");
        cq.createJoin(BusMaterial.class).setMainField("materialId").setJoinField("materialId");
        return selectEntityMap(cq);
    }

    @Override
    public ResultBody importPlan200Data(MultipartFile file, Map params) {
        int i=2;
        try {
            List<BusMaterialPlan200> busMaterialPlan200List = new ArrayList<>();
            List<BusMaterial> busMaterials = new ArrayList<>();
            ImportParams importParams = new ImportParams();
            importParams.setTitleRows(1);
            Long projectId = Long.parseLong(params.get("projectId").toString());
            BusProject project = busProjectService.getById(projectId);
            if (FlymeUtils.isEmpty(project)) {
                return ResultBody.failed("项目信息不存在");
            }
            Integer state = project.getState();
            if (state == 1) {
                return ResultBody.failed("项目已锁定");
            }
            BusVersion version = busVersionService.getLatestVersion(projectId, 1);
            BusVersion version_new = new BusVersion();
            BeanUtils.copyProperties(version, version_new);
            String smallVerion = version_new.getSmallVerion();
            Integer small = TypeUtils.castToInt(smallVerion) + 1;
            if (small < 10) {
                smallVerion = "0" + small;
            } else {
                smallVerion = TypeUtils.castToString(small);
            }
            Long versionId = IdWorker.getId();
            version_new.setVersionId(versionId);
            version_new.setSmallVerion(smallVerion);
            version_new.setProjectId(projectId);
            version_new.setState(0);
            version_new.setVersionType(1);
            version_new.setUserId(OpenHelper.getUserId());
            List<Map<Object, Object>> ExcelList = ExcelImportUtil.importExcel(file.getInputStream(), Map.class, importParams);
            if(commonUtil.ckLevelNo(projectId, ApiConstants.FB_PLANDATA_100, ExcelList)) {
                return ResultBody.failed("存在重复的层级号");
            }
            System.out.println(ExcelList.size());
            project.setVersionId(versionId);
            project.setUserId(OpenHelper.getUserId());
            ResultBody resultBody = pmsApiUtil.chkImpExcelContentForPlanData(ExcelList, ApiConstants.WZ_PLANDATA);
            if(!resultBody.isOk()) {
                return resultBody;
            }
            for (Map<Object, Object> objectObjectMap : ExcelList) {
                i++;
                objectObjectMap.forEach((k, v) -> {
                    if (v == null || v.equals("null")) {
                        v = "";
                        objectObjectMap.put(k, v);
                    }
                });
                BusMaterialPlan200 plan200s = new BusMaterialPlan200();
                BusMaterial busMaterial = new BusMaterial();
                Long materialplan200Id = TypeUtils.castToLong(objectObjectMap.get("材料id"));
                String isAdd = String.valueOf(objectObjectMap.get("是否新增"));
                if (isAdd.equals("否")) {
                    continue;
                }
                Long meaterialId = IdWorker.getId();
                BigDecimal costQuantity200 = BigDecimal.ZERO;
                if(FlymeUtils.isNotEmpty(objectObjectMap.get("200预算成本工程量").toString())){
                    costQuantity200 = BigDecimal.valueOf(Double.parseDouble(objectObjectMap.get("200预算成本工程量").toString()));
                }
//                if (ObjectUtils.isEmpty(objectObjectMap.get("层级号"))) {
//                    return ResultBody.failed("请查看层级号");
//                }
//                if (!objectObjectMap.get("层级号").toString().substring(0, 5).equals(objectObjectMap.get("工程包代码").toString())) {
//                    return ResultBody.failed("层级号与工程包代码不一致");
//                }
                String majorCode = String.valueOf(objectObjectMap.get("专业代码"));
                String majorName = String.valueOf(objectObjectMap.get("专业名称"));
                String projectCode = String.valueOf(objectObjectMap.get("工程包代码"));
                String projectName = String.valueOf(objectObjectMap.get("工程包名称"));
                String materialCode = String.valueOf(objectObjectMap.get("物料代码"));
                String materialWbsCode = String.valueOf(objectObjectMap.get("物料WBS代码"));
                String materialName = String.valueOf(objectObjectMap.get("设备、材料名称"));
                String materiaSpecs = String.valueOf(objectObjectMap.get("型号/规格"));
                String technicalData = String.valueOf(objectObjectMap.get("技术参数或技术说明"));
                String subjectName = String.valueOf(objectObjectMap.get("科目名称"));
                String levelNo = String.valueOf(objectObjectMap.get("层级号"));
                String materialDesc = String.valueOf(objectObjectMap.get("材料项目描述"));
                String contractDesc = String.valueOf(objectObjectMap.get("对外合同清单描述"));
                String materialArea = String.valueOf(objectObjectMap.get("区域"));
                String materialUse = String.valueOf(objectObjectMap.get("系统"));
                String measurementUnit = String.valueOf(objectObjectMap.get("计量单位"));
                String conversionUnit = String.valueOf(objectObjectMap.get("换算单位"));
                String brandName = String.valueOf(objectObjectMap.get("品牌"));
                String remark = String.valueOf(objectObjectMap.get("备注"));
                BigDecimal loss = BigDecimal.ZERO;
                if (FlymeUtils.isNotEmpty(objectObjectMap.get("损耗"))) {
                    loss = BigDecimal.valueOf(Double.parseDouble(objectObjectMap.get("损耗").toString()));
                }
                if (isAdd.equals("是")) {
                    //判断是否为父子关系的新增
                    if (FlymeUtils.isNotEmpty(materialplan200Id)) {
                        BusMaterialPlan200 plan200ls = getById(materialplan200Id);
                        BusMaterial material = busMaterialService.getById(plan200ls.getMaterialId());
                        BeanUtils.copyProperties(material, busMaterial);
                        busMaterial.setParentId(material.getMaterialId());
                        busMaterial.setMaterialId(meaterialId);
                        BeanUtils.copyProperties(plan200ls, plan200s);
                        plan200s.setPlanPurchaseCount(costQuantity200.multiply(loss));
                        plan200s.setEndPurchaseCount(costQuantity200.multiply(loss));
                        plan200s.setDisplayplanPurchaseCount(costQuantity200.multiply(loss));
                        if (FlymeUtils.isNotEmpty(plan200s.getParentId())) {
                            plan200s.setParentId(plan200s.getParentId());
                        } else {
                            plan200s.setParentId(plan200ls.getMaterialPlanId());
                        }
                        plan200s.setMaterialPlanId(IdWorker.getId());
                        plan200s.setCostQuantity200(costQuantity200);
//                        plan200s.setCostdisplayQuantity200(costQuantity200);
                        plan200s.setMaterialId(meaterialId);
                        plan200s.setVersionStatus(0);
                        plan200s.setApplayStatus(ApiConstants.WZ_APPLYSTATUS_AUDIT_WAIT);//待审核状态
                        if(FlymeUtils.isNotEmpty(params.get("dataType"))){
                            plan200s.setPlanType(Integer.parseInt(params.get("dataType").toString()));
                        }
                        plan200s.setVersionId(versionId);
                        busMaterialPlan200List.add(plan200s);
                        busMaterials.add(busMaterial);
                    } else {
                        busMaterial.setMaterialId(meaterialId);
                        busMaterial.setProjectId(projectId);
                        busMaterial.setParentId(0L);
                        busMaterial.setLoss(loss);
                        plan200s.setMaterialPlanId(IdWorker.getId());
                        plan200s.setOrderflg("0");//初始化开口订单状态
                        plan200s.setStatus("2");//
                        plan200s.setApplayStatus(ApiConstants.WZ_APPLYSTATUS_AUDIT_WAIT);//待审核状态
                        if(FlymeUtils.isNotEmpty(params.get("dataType"))){
                            plan200s.setPlanType(Integer.parseInt(params.get("dataType").toString()));
                        }
                        plan200s.setVersionStatus(0);
                        plan200s.setMaterialId(meaterialId);
                        plan200s.setProjectId(projectId);
                        plan200s.setVersionId(versionId);
                        plan200s.setMajorName(majorName);
                        plan200s.setMajorCode(majorCode);
                        plan200s.setPackageName(projectName);
                        plan200s.setPackageNo(projectCode);
                        plan200s.setMaterialWbsCode(materialWbsCode);
                        plan200s.setMaterialDesc(materialDesc);
                        plan200s.setMaterialName(materialName);
                        plan200s.setMaterialCode(materialCode);
                        plan200s.setSubjectName(subjectName);
                        plan200s.setContractDesc(contractDesc);
                        plan200s.setMaterialArea(materialArea);
                        plan200s.setMaterialUse(materialUse);
                        plan200s.setCostQuantity200(costQuantity200);
//                        plan200s.setCostdisplayQuantity200(costQuantity200);
                        plan200s.setMeasurementUnit(measurementUnit);
                        plan200s.setBrandName(brandName);
                        plan200s.setRemark(remark);
                        plan200s.setLoss(loss);
                        plan200s.setTechnicalData(technicalData);
                        plan200s.setMateriaSpecs(materiaSpecs);
                        plan200s.setLevelNo(levelNo);
                        plan200s.setPurchaseCount(BigDecimal.ZERO);
                        plan200s.setZtPurchaseCount(BigDecimal.ZERO);
                        plan200s.setDhPurchaseCount(BigDecimal.ZERO);
                        plan200s.setPlanPurchaseCount(costQuantity200.multiply(loss));
//                        plan200s.setDisplayplanPurchaseCount(costQuantity200.multiply(loss));
                        plan200s.setEndPurchaseCount(costQuantity200.multiply(loss));
                        busMaterialPlan200List.add(plan200s);
                        busMaterials.add(busMaterial);
                    }
                }
            }
            if (busMaterialPlan200List.size() > 0) {
                busMaterialService.saveBatch(busMaterials);
                saveBatch(busMaterialPlan200List);
                busProjectService.saveOrUpdate(project);//更新项目版本
                busVersionService.saveOrUpdate(version_new);//更新此次操作版本
            }else{
                return ResultBody.failed("当前excel没有要处理的数据，请查看");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResultBody.failed("导入失败请核对第"+i+"行数据");
        }
        return ResultBody.ok();
    }

    @Override
    public List<EntityMap> selectInnerOrder(Long purchaseId, Long materialPlanId) {
//        cq.select("bms.contractNo,bmplan.planPurchaseCount,bmplan.endPurchaseCount,bmplan.purchaseCount");
//        cq.createJoin(BusPurchaseDetails.class).setMainField("purchaseDetailsId").setJoinField("purchaseDetailsId");
//        cq.createJoin(BusPurchase.class).setMainAlias("purchase").setJoinField("purchaseId").setMainAlias("bpd").setMainField("purchaseId");
//        cq.createJoin(BusMaterial.class).setMainAlias("material").setMainField("materialId").setMainAlias("bpd").setJoinField("materialId");
//        cq.createJoin(BusMaterialPlan200.class).setMainAlias("bmplan").setMainField("materialId").setMainAlias("material").setJoinField("materialId");
//        cq.eq("bmplan.materialPlanId",materialPlanId);
//        cq.eq("purchase.purchaseId",purchaseId);
        CriteriaQuery cq = new CriteriaQuery<>(BusMaterialPlan200.class);
        cq.select("bmss.busMaterialSrmSubId,bmss.materialPlanId,bmss.contractNo,bmss.orderQty,bmss.orderOutQty,bmss.orderThisTimeQty");
//        cq.createJoin(BusPurchaseDetails.class).setMainField("purchaseDetailsId").setJoinField("purchaseDetailsId");
//        cq.createJoin(BusPurchase.class).setMainAlias("purchase").setJoinField("purchaseId").setMainAlias("bpd").setMainField("purchaseId");
//        cq.createJoin(BusMaterial.class).setMainAlias("material").setMainField("materialId").setMainAlias("bpd").setJoinField("materialId");
        cq.createJoin(BusMaterialSrmSub.class).setMainField("materialPlanId").setJoinField("materialPlanId");
        cq.eq("bmep.materialPlanId", materialPlanId);
        return selectEntityMap(cq);
    }

    @Override
    public List<EntityMap> selectVersionList(Map map) {
        String versionType = (String) map.get("versionType");
        CriteriaQuery<BusMaterialPlan200> cq = new CriteriaQuery(BusMaterialPlan200.class);
        cq.select(BusVersion.class, "versionId", "concat(bigVersion,'.',smallVerion) as versionNo");
        cq.eq("bmep.projectId", map.get("projectId"));
        cq.isNotNull("version.versionId");
        if ("1".equals(versionType)) {
            cq.eq("version.bigVersion", "100");
            cq.ne("version.smallVerion", "00");
        }
        if ("2".equals(versionType)) {
            cq.ne("version.bigVersion", "100");
        }
        cq.createJoin(BusVersion.class).setMainField("versionId").setJoinField("versionId");
        cq.groupBy("bmep.versionId");
        return selectEntityMap(cq);
    }


}
